package leetcode;

/**
 * class Code1115_交替打印2 {
 *   public void foo() {
 *     for (int i = 0; i < n; i++) {
 *       print("foo");
 *     }
 *   }
 *
 *   public void bar() {
 *     for (int i = 0; i < n; i++) {
 *       print("bar");
 *     }
 *   }
 * }
 * 两个不同的线程将会共用一个 Code1115_交替打印2 实例。其中一个线程将会调用 foo() 方法，
 *
 * 另一个线程将会调用 bar() 方法。
 *
 * 请设计修改程序，以确保 "foobar" 被输出 n 次。
 *

 * @date 2020/3/11 0:12
 */
public class Code1115_交替打印 {
    private int n;
    private volatile boolean produced = false;
    public Code1115_交替打印(int n) {
        this.n = n;
    }

    public void foo(Runnable printFoo) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            while(produced){
                Thread.yield();//这里要让出CPU执行权，不然OJ超时,睡眠也行
            }
            // printFoo.run() outputs "foo". Do not change or remove this line.
            printFoo.run();
            produced = true;
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            while(!produced){
                Thread.yield();
            }
            // printBar.run() outputs "bar". Do not change or remove this line.
            printBar.run();
            produced = false;
        }
    }
}
